package cn.swing.ushare.article.webapi.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.swing.ushare.article.service.IArticleService;
import cn.swing.ushare.common.web.JsonResult;
import cn.swing.ushare.pojo.dto.ArticleAddNewDTO;
import cn.swing.ushare.pojo.dto.ArticlePictureAddDTO;
import cn.swing.ushare.pojo.entity.Article;
import cn.swing.ushare.pojo.entity.ArticlePicture;
import cn.swing.ushare.pojo.entity.Category;
import cn.swing.ushare.pojo.vo.*;
import io.swagger.models.auth.In;
import cn.swing.ushare.pojo.vo.ArticleDetailsVO;
import cn.swing.ushare.pojo.vo.ArticleHomeVO;
import cn.swing.ushare.pojo.vo.ArticleSimpleVO;
import cn.swing.ushare.pojo.vo.CategorySimpleVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spring.web.json.Json;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.HashMap;
import java.io.File;
import java.util.List;
import java.util.Map;

import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping(value = "/articles", produces = "application/json;charset=utf-8")
public class ArticleController {

    @Autowired
    private IArticleService articleService;


    private String dirPath;

    /**
     * *********************************** insert **********************************************************************
     */
    //添加类比
    @RequestMapping("/insertCategory")
    public JsonResult<Void> categoryInsertResult(Category category) {
        articleService.insertCategory(category);
        return JsonResult.ok();
    }

    //添加文章
    @RequestMapping("/insertArticle")
    @PreAuthorize("hasAnyAuthority('发表文章')")
    public JsonResult<Void> articleInsertResult(@RequestBody String ruleForm) {
        Article article = articleService.getArticleCover(ruleForm);
        articleService.insertArticle(article);
        System.out.println("article = " + article);
        //根据用户id查询他最新发布的文章并返回文章id
        Integer userId = article.getUserId();
        Integer articleId = articleService.selectCurrentUserNewArticle(userId);
        //根据文章id向表里插入相应的文章图片
        ArticlePicture articlePicture = new ArticlePicture();
        List<String> path = articleService.getPicturePath(ruleForm);
        for (String picturePath : path) {
            articlePicture.setUrl(picturePath);
            articlePicture.setArticleId(articleId);
            articleService.insertArticlePictures(articlePicture);
        }
        return JsonResult.ok();
    }

    //上传图片
    @PostMapping("/uploadArticlePicture")
    public JsonResult<String> upload(MultipartFile picFile) throws Exception {
        System.out.println("picFile = " + picFile);
        String fileName = articleService.uploadPictures(picFile);
        return JsonResult.ok(fileName);

    }


    /**
     * *********************************** delete **********************************************************************
     */

    //删除上传的图片
    @GetMapping("/removePicture")
    public JsonResult<Void> remove(String pictureName) {
        articleService.removePicture(pictureName);
        return JsonResult.ok();
    }

    //操作：删除文章
    @RequestMapping("/delete")
    @PreAuthorize("hasAnyAuthority('文章删除')")
    public JsonResult<Void> articleDeleteResult(Long id) {
        articleService.deleteArticleById(id);
        return JsonResult.ok();
    }

    //批量删除文章
    @RequestMapping("/batchDelete")
    public JsonResult<Void> batchDeleteArticleResult(Long[] ids) {
        for (Long id : ids) {
            articleService.deleteArticleById(id);
        }
        return JsonResult.ok();
    }

    //删除类别
    @RequestMapping("/deleteCategory")
    public JsonResult<Void> categoryDeleteResult(Long id) {
        articleService.deleteCategoryById(id);
        return JsonResult.ok();
    }

    //批量删除类别
    @RequestMapping("/batchDeleteCategory")
    public JsonResult<Void> batchDeleteCategoryResult(Long[] ids) {
        for (Long id : ids) {
            articleService.deleteCategoryById(id);
        }
        return JsonResult.ok();
    }


    /**
     * *********************************** select **********************************************************************
     */

    //查询文章列表显示到后台页面
    @GetMapping("/categoryLimitList")
    public JsonResult<List<CategorySimpleVO>> selectCategoryList(Integer currentPage) {
        System.out.println("currentPage = " + currentPage);
        List<CategorySimpleVO> categorySimpleVOS = articleService.selectSimpleCategoryList(currentPage);
        return JsonResult.ok(categorySimpleVOS);
    }

    //查询所有文章类别
    @RequestMapping("/categoryMenu")
    public JsonResult<List<CategorySimpleVO>> selectCategoryListResult(Integer current) {
        List<CategorySimpleVO> categorySimpleVOS = articleService.selectSimpleCategory(current);
        return JsonResult.ok(categorySimpleVOS);
    }

    //根据类别名称查询类别
    @PostMapping("/categoryByName")
    public JsonResult<List<CategorySimpleVO>> selectCategoryByNameListResult(Integer currentPage,String categoryName) {
        List<CategorySimpleVO> categorySimpleVOS = articleService.selectSimpleCategoryByName(currentPage, categoryName);
        return JsonResult.ok(categorySimpleVOS);
    }
    //查询根据当前条件分类的总条数
    @GetMapping("selectCategoryCount")
    public JsonResult<Integer> selectCategoryCount(String categoryName){
        Integer count = articleService.selectCategoryCount(categoryName);
        return JsonResult.ok(count);
    }

    //查询文章显示到前台频道
    @PostMapping("/articleChannel")
    public JsonResult<List<ArticleHomeVO>> selectArticleToChannel(Integer categoryId,Integer sortId){
        System.out.println("categoryId = " + categoryId);
        System.out.println("sortId = " + sortId);
        List<ArticleHomeVO> articleHomeVOS = articleService.selectArticleToChannel(categoryId, sortId);
        return JsonResult.ok(articleHomeVOS);
    }

    @GetMapping("/countAllArticle")
    public JsonResult<Integer> countAllArticle() {
        return JsonResult.ok(articleService.countAllArticle());
    }


    //查询前十文章根据浏览量
    @GetMapping("/topTenByViewCount")
    public JsonResult<List<ArticleTopSimpleVO>> topTenList() {
        List<ArticleTopSimpleVO> articleTopSimpleVO = articleService.topTenList();
        return JsonResult.ok(articleTopSimpleVO);
    }

    //查询所有文章
    @RequestMapping("/list")
    public List<ArticleDetailsVO> articleListResult(Integer page, Integer index, Integer type, Integer category) {
        System.out.println("page = " + page);
        System.out.println("index = " + index);
        System.out.println("type = " + type);
        System.out.println("category = " + category);
        return articleService.getAllArticles((page - 1) * 10, index, type, category);
    }


    //根据文章状态查询文章
    @RequestMapping("/stateList")
    public JsonResult<List<ArticleDetailsVO>> articleStateListResult(Long state) {
        List<ArticleDetailsVO> articleDetailsVOS = articleService.selectArticleByState(state);
        return JsonResult.ok(articleDetailsVOS);
    }

    //根据文章类型查询文章
    @RequestMapping("/articlesType")
    public JsonResult<List<ArticleDetailsVO>> articleTypeListResult(Integer type) {
        List<ArticleDetailsVO> articleDetailsVOS = articleService.selectArticleByType(type);
        return JsonResult.ok(articleDetailsVOS);
    }

    //查询所有文章类别
//    @RequestMapping("/categoryMenu")
//    public JsonResult<List<CategorySimpleVO>> selectCategoryListResult(Integer current) {
//        List<CategorySimpleVO> categorySimpleVOS = articleService.selectSimpleCategory(current);
//        return JsonResult.ok(categorySimpleVOS);
//    }

    //根据类别名称查询类别
    @GetMapping("/categoryByName")
    public JsonResult<List<CategorySimpleVO>> selectCategoryByNameListResult(String name) {
        List<CategorySimpleVO> categorySimpleVOS = articleService.selectSimpleCategoryByName(name);
        return JsonResult.ok(categorySimpleVOS);
    }

    //根据文章id查询文章
    @RequestMapping("/articlesCategory")
    public JsonResult<List<ArticleDetailsVO>> articleCategoryListResult(Integer categoryId) {
        List<ArticleDetailsVO> articleDetailsVOS = articleService.selectArticleByCategoryId(categoryId);
        return JsonResult.ok(articleDetailsVOS);
    }

    //根据文章标题查询文章
    @RequestMapping("/articlesTitle")
    public JsonResult<List<ArticleDetailsVO>> articleTitleListResult(String title,Integer currentPage) {
        System.out.println("title = " + title);
        System.out.println("currentPage = " + currentPage);
        List<ArticleDetailsVO> articleDetailsVOS = articleService.selectArticleByTitle(title,currentPage);
        return JsonResult.ok(articleDetailsVOS);
    }

    //询根据文章标题查询文章总条数
    @GetMapping("totalArticleByTitle")
    public JsonResult<Integer> articleCountByTitle(String title){
        Integer countByTitle = articleService.articleCountByTitle(title);
        return JsonResult.ok(countByTitle);
    }

    // 根据ID获取文章详情
    @GetMapping("/articleDetails")
    public JsonResult<ArticleDetailsVO> articleDetailsResult(Integer id) {
        ArticleDetailsVO articleDetails = articleService.selectArticleDetailsById(id);
        return JsonResult.ok(articleDetails);
    }

    // 根据文章ID获取文章的图片
    @GetMapping("/articlePictures")
    public JsonResult<List<String>> selectArticlePictures(Integer id) {
        List<String> list = articleService.selectArticlePicturesById(id);
        return JsonResult.ok(list);
    }

    //根据用户ID获取所著文章信息
    @GetMapping("/articleSimple")
    public JsonResult<List<ArticleSimpleVO>> selectArticleSimpleById(Integer id) {
        List<ArticleSimpleVO> articleSimpleVOS = articleService.selectArticleSimpleById(id);
        return JsonResult.ok(articleSimpleVOS);
    }

    //查询文章显示到文章首页
    @GetMapping("/articlesDetailsHome")
    public JsonResult<List<ArticleHomeVO>> selectArticleDetailsHome() {
        System.out.println("ArticleController.selectArticleDetailsHome()");
        List<ArticleHomeVO> articleHomeVOS = articleService.selectArticleHome();
        return JsonResult.ok(articleHomeVOS);
    }

    //查询热门文章
    @GetMapping("/hotArticlesDetails")
    public JsonResult<List<ArticleHomeVO>> selectHotArticles() {
        List<ArticleHomeVO> articleHomeVOS = articleService.selectHotArticle();
        return JsonResult.ok(articleHomeVOS);
    }

    @GetMapping("/isLoved")
    public JsonResult<Integer> selectIsLovedByUserIdAndArticleId(Integer articleId, Integer userId) {
        Integer result = articleService.selectIsLovedByUserIdAndArticleId(articleId, userId);
        return JsonResult.ok(result);
    }

    @GetMapping("/deleteIsLoved")
    public JsonResult<Integer> deleteIsLovedByUserIdAndArticleId(Integer articleId, Integer userId) {
        Integer result = articleService.deleteIsLovedByUserIdAndArticleId(articleId, userId);
        return JsonResult.ok(result);
    }

    @PostMapping("/insertIsLoved")
    public JsonResult<Integer> insertIsLovedByUserIdAndArticleId(@Param("articleId") Integer articleId, @Param("userId") Integer userId) {
        Integer result = articleService.insertIsLovedByUserIdAndArticleId(articleId, userId);
        return JsonResult.ok(result);
    }

    @PostMapping("/addLoveCounts")
    public JsonResult<Integer> addArticleLoveCountById(@Param("id") Integer id) {
        Integer result = articleService.addArticleLoveCountById(id);
        return JsonResult.ok(result);
    }

    @PostMapping("/addUserLoveCount")
    public JsonResult<Integer> addUserLoveCount(@Param("userId") Integer userId){
        Integer result = articleService.addUserLoveCount(userId);
        return JsonResult.ok(result);
    }

    @PostMapping("/subUserLoveCount")
    public JsonResult<Integer> subUserLoveCount(@Param("userId") Integer userId){
        Integer result = articleService.subUserLoveCount(userId);
        return JsonResult.ok(result);
    }

    @PostMapping("/subLoveCounts")
    public JsonResult<Integer> subArticleLoveCountById(@Param("id") Integer id) {
        Integer result = articleService.subArticleLoveCountById(id);
        return JsonResult.ok(result);
    }

    @PostMapping("/addCollection")
    public JsonResult<Integer> addArticleCollection(@Param("articleId") Integer articleId, @Param("userId") Integer userId) {
        Integer result = articleService.addArticleCollection(articleId, userId);
        return JsonResult.ok(result);
    }

    @PostMapping("/deleteCollection")
    @PreAuthorize("hasAnyAuthority('文章删除')")
    public JsonResult<Integer> deleteArticleCollection(@Param("articleId") Integer articleId, @Param("userId") Integer userId) {
        Integer result = articleService.deleteArticleCollection(articleId, userId);
        return JsonResult.ok(result);
    }

    @PostMapping("/selectArticleCollectionStatus")
    public JsonResult<Integer> selectArticleCollectionStatus(@Param("articleId") Integer articleId, @Param("userId") Integer userId) {
        Integer result = articleService.selectArticleCollectionStatus(articleId, userId);
        return JsonResult.ok(result);
    }

    @PostMapping("/addCollectionCounts")
    public JsonResult<Integer> addArticleCollectionCounts(@Param("id") Integer id) {
        Integer result = articleService.addArticleCollectionCounts(id);
        return JsonResult.ok(result);
    }

    @PostMapping("/subCollectionCounts")
    public JsonResult<Integer> subArticleCollectionCounts(@Param("id") Integer id) {
        Integer result = articleService.subArticleCollectionCounts(id);
        return JsonResult.ok(result);
    }

    @GetMapping("/listCollections")
    public JsonResult<List<ArticleSimpleVO>> selectArticleCollectionByUserId(Integer userId) {
        List<ArticleSimpleVO> list = articleService.selectArticleCollectionByUserId(userId);
        return JsonResult.ok(list);
    }

    @RequestMapping("/countArticles")
    public JsonResult<Integer> selectArticleToChannel(Integer index, Integer type, Integer category) {
        return JsonResult.ok(articleService.articlesCount(index, type, category));
    }


    //查询文章显示到前台频道
    @PostMapping("/articleRecommend")
    public JsonResult<List<ArticleHomeVO>> selectArticleToRecommend(Integer categoryId) {
        List<ArticleHomeVO> articleRecommends = articleService.selectArticleToRecommend(categoryId);
        return JsonResult.ok(articleRecommends);
    }


    @PostMapping("/addArticleViews")
    public JsonResult<Integer> addArticleViews(Integer id) {
        Integer result = articleService.addArticleViews(id);
        return JsonResult.ok(result);
    }


    @GetMapping("/search")
    public JsonResult<List<ArticleResultVO>> searchArticles(String keyword, Integer page) {
        List<ArticleResultVO> list = articleService.searchArticles(keyword, (page - 1) * 9);
        return JsonResult.ok(list);
    }

    @GetMapping("/searchCounts")
    public JsonResult<Integer> searchArticles(String keyword) {
        Integer result = articleService.getSearchCounts(keyword);
        return JsonResult.ok(result);
    }

    @PostMapping("/getNewestArticle")
    public JsonResult<Integer> getNewestArticle(Integer userId) {
        Integer result = articleService.selectCurrentUserNewArticle(userId);
        return JsonResult.ok(result);
    }
}
